/**
 * Created by tanbingqin on 2020/10/23.
 */
import { messages } from "share/common";
import React from "react";
import { Icon, Button, Row, Col, message } from "antd";
import SignatureCanvas from "react-signature-canvas";
import "styles/components/template/signature/signature.scss";
import Condition from "components/condition";
const If = Condition.If;
import errorMessage from "share/errorMessage";
import signatureService from "components/template/signature/signature.service";

/**
 * pointer-events有浏览器兼容性问题，所以画布的placeholder的height，line-height不能直接覆盖全部画布
 * 现在使用/api/upload/attachment，则会自动生成hash，不会有文件重名的情况
 * 如果使用的url是/api/upload/static/attachment，不会自动在文件名后生成hash
 *
 * ps：如果安全配置那里配置了不允许上传png类型，那么这个签名就不能上传了
 */

class Signature extends React.Component {
  state = {
    isShowPlaceholder: true,
    loading: false,
  };

  componentDidMount() {}

  handleClear = () => {
    this.sigCanvas.clear();
    this.setState({ isShowPlaceholder: true });
  };

  handleBegin = () => {
    this.setState({ isShowPlaceholder: false });
  };

  handleTrim = () => {
    if (this.sigCanvas.isEmpty()) {
      message.error(messages("common-1.key1381") /*请写入签名*/);
      return;
    }
    //let base64String = this.sigCanvas.getTrimmedCanvas().toDataURL("image/png");  //trimmed在部分浏览器型号下是透明的
    let base64String = this.sigCanvas.getCanvas().toDataURL("image/png"); //带有底色的图片
    let toBlob = this.base64ToBlob(base64String);
    let toFile = new File([toBlob], "signature.png");
    let formData = new FormData();
    formData.append("attachmentType", "OTHER");
    formData.append("file", toFile);
    this.setState({ loading: true });
    signatureService
      .handleImageUpload(formData)
      .then((res) => {
        this.setState({ loading: false });
        this.props.onChange(res.data);
      })
      .catch((err) => {
        errorMessage(err.response);
        this.setState({ loading: false });
      });
  };

  base64ToBlob = (base64String) => {
    let parts = base64String.split(";base64,");
    let contentType = parts[0].split(":")[1];
    let raw = window.atob(parts[1]);
    let rawLength = raw.length;
    let uInt8Array = new Uint8Array(rawLength);
    for (let i = 0; i < rawLength; ++i) {
      uInt8Array[i] = raw.charCodeAt(i);
    }
    return new Blob([uInt8Array], {
      type: contentType,
    });
  };

  handleCancel = () => {
    this.props.onCancel();
  };

  render() {
    const { width, height } = this.props;
    const { isShowPlaceholder, loading } = this.state;
    return (
      <div className="signature-block">
        <If value={isShowPlaceholder}>
          <div className="canvas-placeholder" style={{ width, height: 20, marginTop: `${height / 2 - 10}px` }}>
            {messages("common-1.key1382") /*请在此区域拖动鼠标签名*/}
          </div>
        </If>
        <SignatureCanvas
          canvasProps={{
            width,
            height,
          }}
          backgroundColor="#e8e8e8"
          onBegin={this.handleBegin}
          ref={(ref) => (this.sigCanvas = ref)}
        />
        <div style={{ marginTop: 5, height: 35 }}>
          <Button loading={loading} onClick={this.handleTrim}>
            {messages("common.save") /*保存*/}
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={this.handleCancel}>
            {messages("common.cancel") /*取消*/}
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={this.handleClear}>
            {messages("common.clear") /*清空*/}
          </Button>
        </div>
      </div>
    );
  }

  static propTypes = {
    width: React.PropTypes.number, //画布宽度，不可设置百分比
    height: React.PropTypes.number, //画布高度，不可设置百分比 至少要远高于placeholder块的高度20px
    onChange: React.PropTypes.func,
    onCancel: React.PropTypes.func,
  };

  static defaultProps = {
    width: 500,
    height: 200,
    onChange: () => {},
    onCancel: () => {},
  };
}

export default Signature;
